<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\common;

use app\model\activity\free\FreeRuleProduct;
use app\model\activity\seckill\StoreSeckillProduct;
use app\model\product\product\StoreProduct;
use app\model\product\sku\StoreProductAttrValue;
use app\model\product\sku\StoreProductStockRelation;
use crmeb\exceptions\ApiException;
use think\facade\Db;

/**
 * 库存处理工具类
 */
class InventoryTool
{
    private $storeProductStockRelation;
    /**
     * @return InventoryTool
     * 静态调用入口
     */
    public static function init() : InventoryTool
    {
        return new static();
    }

    /**
     * @param $method
     * @param $productId
     * @param $number
     * @return void
     * 库存处理唯一入口
     */
    public function inventory($method, $productId, $sku, $number)
    {

        //获取扣减库存方式
        $stockType = StoreProduct::where('id', $productId)->value('store_type');
        //获取库存对象
        $storeProductStockRelation = StoreProductStockRelation::where([
            ['product_id', '=', $productId],
            ['product_attr_value_unique', '=', $sku],
        ])->find();

        Db::transaction(function () use ($stockType, $method, $productId, $sku, $number, $storeProductStockRelation) {

            // 确认订单或者创建订单的时候,用来处理库存
            if($stockType == 1 && in_array($method, ['create', 'again'])
                || ($stockType == 2 && in_array($method, ['paySuccess']))
            ) {
                $storeProductStockRelation->in_stock -= $number;
                $storeProductStockRelation->pending_sale_stock += $number;
            }
            // 当后台进行发货的时候
            if ($method == 'shipping') {
                $storeProductStockRelation->total_stock -= $number;
                $storeProductStockRelation->pending_sale_stock -= $number;
                $storeProductStockRelation->has_sale_stock += $number;
            }
            // 当用户取消的时候
            if ($method == 'cancel') {
                $storeProductStockRelation->in_stock += $number;
                $storeProductStockRelation->pending_sale_stock -= $number;
            }
            // 当后台退款的时候
            if ($method == 'refund') {
                $storeProductStockRelation->in_stock += $method;
                $storeProductStockRelation->refund_onway_stock += $number;
            }

            $storeProductStockRelation->save();


            // 维护 store_product 表库存
            StoreProduct::where('id', $productId)->inc('sales', $number)->update();
            // 维护 规格表
            StoreProductAttrValue::where('unique', $sku)->inc('sales', $number)->update();

        });

    }


    /**
     * 关联秒杀库存
     *
     * @param $method
     * @param $orderItem
     * @return void
     */
    public function syncSeckillStock($method, $orderItem)
    {
        Db::transaction(function () use ($method, $orderItem) {

            // 处理 秒杀库存
            // 当支付成功的时候, 秒杀库存减1
            if ($method == 'paySuccess' && !empty($orderItem['seckill_id'])) {
                $seckillProduct = StoreSeckillProduct::hasWhere('seckill', function ($query) {
                    $query->where('start_time', '<=', time())->where('end_time', '>', time())->where('is_del', 0)->where('status',1);
                })->where('product_attr_value_unique', $orderItem['product_attr_value_unique'])->where('seckill_id', $orderItem['seckill_id'])->find();

                if (!$seckillProduct || $seckillProduct->count < $orderItem['nums']) {
                    throw new ApiException(31010);
                }
                $seckillProduct->count -= $orderItem['nums'];
                $seckillProduct->save();
            }

        });

    }

    /**
     *
     * 管理满赠库存
     *
     * @param $method
     * @param $orderItem
     * @return void
     */
    public function syncFreeStock($method, $orderItem)
    {
        Db::transaction(function () use ($method, $orderItem) {
            // 处理 秒杀库存
            // 当支付成功的时候, 秒杀库存减1
            if ($method == 'paySuccess' && !empty($orderItem['free_json'])) {
                $freeArr = json_decode($orderItem['free_json'], true) ?? [];
                foreach ($freeArr as $item) {
                    $free_rule_product = FreeRuleProduct::where(
                        'product_attr_value_unique',
                        $item['product_attr_value_unique']
                    )->where('free_rule_id', $item['free_rule_id'])->find();
                    if (!$free_rule_product) {
                        throw new ApiException(31010);
                    }
                    $free_rule_product->activity_count -= $item['give_count'];
                    $free_rule_product->save();
                }
            }
        });
    }

//    /**
//     * 适用于确认订单,支付成功时候的库存扣减情况
//     */
//    private function outbound($productId, $sku, $number)
//    {
//        Db::transaction(function () use ($productId, $sku, $number) {
//            //新增出库在途，减去总库存
//            $storeProductStockRelation->in_stock -= $number;
//            $storeProductStockRelation->pending_sale_stock += $number;
//            $storeProductStockRelation->save();
//
//            //新增库存出库记录
//        });
//
//    }
//
//    /**
//     * 适用于发货时候的用来处理库存关系
//     */
//    public function inbound($productId, $sku, $number) {
//        Db::transaction(function () use ($productId, $sku, $number) {
//            //新增出库在途，减去总库存
//            $storeProductStockRelation->total_stock -= $number;
//            $storeProductStockRelation->pending_sale_stock -= $number;
//            $storeProductStockRelation->has_sale_stock += $number;
//            $storeProductStockRelation->save();
//
//            //新增库存出库记录
//        });
//    }
//
//    /**
//     * 库存盘点
//     */
//    public function stock() {
//        /**
//         * 库存计算方式
//         * 总库存=在库库存-待出库存+已售库存+退件在途库存
//         */
//
//    }

}